package DepthCoverage;
use lib "$ENV{MYSQL_DRAW}/lib";
use MyTools;
use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
 
@ISA = qw(Exporter AutoLoader);

@EXPORT = qw( readDepthCoverage );

use Data::Dumper;

sub readDepthCoverage {
	my ($dbh, $path_prefix, $suffix, $modifier, $field_list) = @_;
	open(FIN, "cut -f1-100 $path_prefix.$suffix |") || die "cannot open $path_prefix.$suffix\n";
	my %hash;
	my $header_line = <FIN>;
	my @headers = split(/\t/, $header_line);
	my $value_line = <FIN>;
	my @values = split(/\t/, $value_line);
	close FIN;
	my $RV; # Returned Value $RV->{metric_id}
	my $VR; # revers key-value of $RV, such that $VR->{field_name} = metric_id
	foreach my $fd (@{$field_list}) {
		my $metric_id = MyTools::fetchrow1col1_arrayref($dbh, "select MIID from MetricInfo where ", {'FieldName' => $fd, 'Modifier' => $modifier}) or die "Field $fd $modifier not found\n";
#		printf STDERR "$fd\t$metric_id\n";
		my $fd_val = "NA";
		for (my $i=0; $i < scalar @headers; $i++) {
			if ($headers[$i] eq $fd) {
				$fd_val = $values[$i];
				last;
			}
		}
		$RV->{$metric_id}->{'value'} = $fd_val;
		$RV->{$metric_id}->{'field_name'} = $fd;
		$VR->{$fd} = $metric_id;
	}
	return ($RV, $VR);
}

sub get_metric_id {
	my ($dbh, $modifier, $fd) = @_;
	my $sql = "select Metric_id from MetricInfo where Field_name = \"$fd\" and Modifier = \"$modifier\"";
	return fetchrow1col1_arrayref($dbh, $sql);
}

sub fetchrow1col1_arrayref {
  my ($dbh, $sql) = @_;
  my $sh = $dbh->prepare($sql);
  $sh->execute();
  my $ary_ref = $sh->fetchrow_arrayref();
  $sh->finish();
  return $ary_ref->[0];
}

sub my_fetchall_arrayref {
  my ($dbh, $sql) = @_;
  my $sh = $dbh->prepare($sql);
  $sh->execute();
  my $ary_ref = $sh->fetchall_arrayref();
  $sh->finish();
  return $ary_ref;
}

1;

